# coding=UTF-8
from google.appengine.ext.db import djangoforms as forms
from google.appengine.ext import db
from models import Post, Comment, Event,Category,Tag
from django.shortcuts import render_to_response
from django.template import RequestContext
from google.appengine.api import users
from django.http import HttpResponseRedirect, HttpResponseForbidden,HttpResponse,HttpResponseNotFound
from django.core.paginator import Paginator, InvalidPage
from django.views.decorators.vary import vary_on_headers
from django.views.decorators.cache import cache_control,cache_page
from django.utils.encoding import force_unicode,smart_str
from google.appengine.api import memcache
from django.core.urlresolvers import reverse


import datetime,logging,time
from authorized import admin_required,login_required
import urllib
from utility import permalink
import settings
from django import forms as djangoforms

class PostForm(forms.ModelForm):
#    tags = djangoforms.MultipleChoiceField(choices=('tag1','tag2',),)

    class Meta:
        model = Post          
        exclude = ['categories','tags','author','lastCommentedDate', 'commentcount','visitcount', 'lastModifiedDate', 'lastModifiedBy', ]

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        exclude = ['post', 'date', 'author', 'userIp', 'lastModifiedDate', 'lastModifiedBy', ]


@admin_required
def add_post(request):
    user=users.get_current_user()
    if request.method == 'GET':
        form = PostForm({'authorEmail':str(user.email()),})
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            if not post.slug:
                try:
                    post.slug=permalink.get_slug(post.title)
                except:
                    pass
            timestamp=str(time.time())[:10]
            key_name='post_'+timestamp            
            
            new_post=Post(
                                  key_name=key_name,
                                  parent=post.category,
                                  category=post.category,
                                  title =post.title,
                                  content =post.content,
                                  author =user,
                                  authorEmail =post.authorEmail,
                                  slug =post.slug,
                                  entryType=post.entryType,
                                  isPublished=post.isPublished,
#                                  tags=tags,
#                                  categories=categories,
                        )
            new_post.put()
            #flush cache, for the new post appears in the main page            
            memcache.flush_all()
            return HttpResponseRedirect(post.get_permalink())
    
    template_values={'form': form, 'users':users, }
    return render_to_response('blog/add_post.html', template_values,)

@cache_control(must_revalidate=True, max_age=60*60)#cache_control 告诉缓存对每次访问都重新验证缓存并在最长 3600 秒内保存所缓存版本
@vary_on_headers('User-Agent','Cookie')
def view_post(request, key):
    key=force_unicode(urllib.unquote(smart_str(key))) 
    post= Post.get(db.Key(key))
    if post:
        comments = post.comment_set.order('-date')
        user = users.get_current_user()
        if request.method == 'GET':
            if user:
                form = CommentForm({'user':str(user.nickname()), 'authorEmail':str(user.email()),})
            else:
                form = CommentForm()
            if not post.slug:
                #adapt old style url pages
                try:
                    post.slug=permalink.get_slug(post.title)
                    post.put()
                except :
                    memcache.flush_all()
                    return HttpResponseRedirect(reverse(list_post))
          
            post.visitcount+=1
            post.put()
       
        if request.method == 'POST':
            form = CommentForm(request.POST)
            if form.is_valid():
                comment = form.save(commit=False)
                timestamp=str(time.time())[:10]
                key_name='comment_'+timestamp
                
                if 'REMOTE_ADDR' in request.META:
                    comment.userIp = request.META['REMOTE_ADDR']
                if user:
                    comment.author = user
                    comment.authorEmail = str(user.email())
                    comment.user = str(user.nickname())
                    
                new_comment=Comment(
                                    key_name=key_name,
                                    post = post,
                                    user = comment.user,
                                    author = comment.author,
                                    authorEmail = comment.authorEmail,
                                    authorWebsite = comment.authorWebsite,
                                    userIp = comment.userIp,
                                    content = comment.content,
                                    parent=post,
                                    )
                new_comment.put()
                #flush cache, for that the new comment appears in the post page            
                memcache.flush_all()
                return HttpResponseRedirect(post.get_permalink()+'#comments')
                
        template_values = {
                  'users' : users,
                  'post' : post,
                  'comments': comments,
                  'tags':db.get(post.tags),
                  'form' : form,
                  
        }
        return render_to_response('blog/view_post.html', template_values,)
    else:
        return HttpResponseNotFound()

@cache_control(must_revalidate=True, max_age=60*60)#cache_control 告诉缓存对每次访问都重新验证缓存并在最长 3600 秒内保存所缓存版本
@vary_on_headers('User-Agent','Cookie')
def view_post_perma(request,*args,**kargs):    
    slug=kargs['slug']  
    slug=force_unicode(urllib.unquote(smart_str(slug))) 
    post = Post.all().filter("slug =", slug).get()
    if post:
        return view_post(request,str(post.key()))
    else:
        memcache.flush_all()        
        return HttpResponseRedirect(reverse(list_post))

@admin_required
def edit_post(request, key):
    key=force_unicode(urllib.unquote(smart_str(key))) 
    user=users.get_current_user()
    post=Post.get(db.Key(key))
    
    if post:
        if post.author==users.get_current_user() or users.is_current_user_admin():
            if request.method == 'POST':
                form = PostForm(request.POST)
                if form.is_valid():
                    formPost=form.save(commit=False)
                    post.title=formPost.title
                    post.content=formPost.content
                    post.authorEmail=formPost.authorEmail
#                    post.category=formPost.category
                    post.entryType=formPost.entryType
                    post.category=formPost.category                    
                    post.isPublished=formPost.isPublished
                    post.slug=formPost.slug
                    post.lastModifiedBy=user
                    post.lastModifiedDate=datetime.datetime.now()
                    post.put()
                    #make the edited post show up
                    memcache.flush_all()
                    return HttpResponseRedirect(post.get_permalink())
            else:
                if post.category:
                    category_key=post.category.key()
                else:
                    category_key=None
                
                data={
                      
                      'title':post.title,
                      'content':post.content,
                      'authorEmail':post.authorEmail,
#                      'category':post.category,
                      'entryType':post.entryType,
                      'category':category_key,
                      'slug':post.slug,
                      'isPublished':post.isPublished,
                      }
                form=PostForm(data)
            template_values={'form': form, 'users':users, }
            return render_to_response('blog/add_post.html', template_values,)
    
    return HttpResponseNotFound()
    
@admin_required
def delete_post(request, key):
    key=force_unicode(urllib.unquote(smart_str(key))) 
    post=Post.get(db.Key(key))
    if post:        
        post.delete()
        #flush cache in order to update the post list
        memcache.flush_all()
        return HttpResponseRedirect(reverse(list_post))
    return HttpResponseForbidden()

@cache_control(must_revalidate=True, max_age=60*60)#cache_control 告诉缓存对每次访问都重新验证缓存并在最长 3600 秒内保存所缓存版本
@vary_on_headers('User-Agent','Cookie')
def list_post(request, page=1,):
    page =int(page)
    object_list=Post.all().order('-date')    
    return list_generic(request, page, object_list)

@cache_control(must_revalidate=True, max_age=60*60)
@vary_on_headers('User-Agent','Cookie')
def category(request,category,page=1):
    page =int(page)
    category = force_unicode(urllib.unquote(smart_str(category))) 
    searchCategory=Category.get_by_key_name('category_'+category)
    if not searchCategory:
        return HttpResponseNotFound()
    object_list=searchCategory.post_set.order('-date')
    return list_generic(request, page, object_list)

@login_required
def delete_comment(request,key):
    comment=Comment.get(key)
    if comment:
        if users.get_current_user()==comment.author or users.is_current_user_admin():
                post=comment.post
                comment.delete()
                #flush cache in order to update the comment list
                memcache.flush_all()
                return HttpResponseRedirect(post.get_permalink()+'#comments')
        else:
            return HttpResponseForbidden()
    else:
        return HttpResponseForbidden()
    
def logout(request):
    return HttpResponseRedirect(users.create_logout_url(reverse(list_post)))

def login(request):
    return HttpResponseRedirect(users.create_login_url(reverse(list_post,args=[1,])))

def event(request):
    events= Event.all().order('-created')
    template_values={'users':users,'events':events ,}
    return render_to_response('event.html',template_values)

@admin_required
def import_wxp(request):
    if request.method == 'POST':
        wxpfile=request.FILES['file']
        try:
            from import_wxp.parseWp import Import,Importer
        except:
            return HttpResponseForbidden()
        importer=Importer(wxpfile)
        importer.import2Gae()
        memcache.flush_all()
        return HttpResponseRedirect(reverse(list_post))
        
    else:
        pass
        
    template_values={'users':users,}
    return render_to_response('import.html',template_values)

@admin_required
def export_wxp(request):
    try:
        base_url=settings.BASE_URL
    except:
        base_url=''
    categories=Category.all()
    tags=Tag.all()    
    posts = Post.all().order('-date')
    items=[]
    for post in posts:
        item={}
        item['post']=post
        comments=post.comment_set.order('-date')
        item['comments']=comments
        item['tags']=db.get(post.tags)
        item['category']=post.category.name
        items.append(item)
        
    response=render_to_response('wordpress.xml',locals())
    filename='wordpress.xml'
    response['Content-Disposition'] = 'attachment; filename="%s"'%filename
    response['Content-Type'] = 'application/octet-stream'
    return response

#############################################################33
def list_generic(request, page=1, object_list=[]):
    page =int(page)
    paginator=Paginator(object_list, 20, orphans=5)
    page_obj=paginator.page(page)
    dict = {'posts':page_obj.object_list,
            'is_paginated': page_obj.has_other_pages(),
            'results_per_page': paginator.per_page,
            'has_next': page_obj.has_next(),
            'has_previous': page_obj.has_previous(),
            'page': page_obj.number,
            'next': page_obj.next_page_number(),
            'previous': page_obj.previous_page_number(),
            'first_on_page': page_obj.start_index(),
            'last_on_page': page_obj.end_index(),
            'pages': paginator.num_pages,
            'hits': paginator.count,
            'page_range': paginator.page_range,
            'users':users,
    }
    return render_to_response('blog/list_post.html', dict)